package com.wmlive.hhvideo.common.base;

import android.support.annotation.LayoutRes;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.wmlive.hhvideo.heihei.channel.ISinaLoginView;
import com.wmlive.hhvideo.heihei.channel.IWechatLoginView;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.widget.AppToolbar;
import com.wmlive.hhvideo.widget.StatusView;
import com.wmlive.networklib.entity.LoginInvalidEvent;
import com.wmlive.networklib.util.RxBus;

import cn.wmlive.hhvideo.R;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

/**
 * Created by vhawk on 2017/5/19.
 * Modify by lsq
 * DcBaseFragment，含根布局(包括Toolbar和Content)
 * 大部分页面都继承自这个类，如果有自己特定的布局，可以直接继承{@link BaseCompatActivity}
 */

public abstract class DcBaseActivity<P extends IBasePresenter> extends BaseCompatActivity<P> implements
        StatusView.OptionClickListener, IWechatLoginView, ISinaLoginView {

    /**
     * 存放订阅的容器,方便统一解除订阅
     */
    CompositeDisposable compositeDisposable;

    protected RelativeLayout rlRootView;
    protected FrameLayout contentView;
    protected AppToolbar toolbar;  //不要在自己的布局文件中加入toolbar
    protected ViewStub vsToolbar;
    private StatusView statusView;
    private boolean isRelativeMode;  //是否是toolbar与contentView是叠加模式，true可实现toolbar渐变透明度效果
    private int pageStatus = StatusView.STATUS_NORMAL;

    @Override
    void initBaseView() {
        super.initBaseView();
        getDelegate().setContentView(R.layout.view_base_layout);
        rlRootView = (RelativeLayout) findViewById(R.id.rlRootView);
        vsToolbar = (ViewStub) findViewById(R.id.vs_toolbar);
        contentView = (FrameLayout) findViewById(R.id.fl_page_container);
        setContentView(getLayoutResId());
        String t = setTitle();
        if (!TextUtils.isEmpty(t)) {
            initToolbar(t, true, 0);
        }
        changeDecorView(0);
    }

    @Override
    protected void initData() {
        super.initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        onLoginInvalidEvent();
    }


    private void onLoginInvalidEvent() {
        // 登录失效，弹起登录对话框
        getCompositeDisposable()
                .add(toFlowable(LoginInvalidEvent.class)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<LoginInvalidEvent>() {
                            @Override
                            public void accept(LoginInvalidEvent o) throws Exception {
                                showReLogin();
                            }
                        }));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoad();
    }

    protected CompositeDisposable getCompositeDisposable() {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        return compositeDisposable;
    }

    protected <T> Flowable<T> toFlowable(Class<T> type) {
        return RxBus.getInstance().toFlowable(type);
    }

    /**
     * 初始化Toolbar
     *
     * @param title    标题
     * @param showBack 是否显示返回箭头
     * @param resId    logo
     */
    final void initToolbar(String title, boolean showBack, int resId) {
        if (!TextUtils.isEmpty(title) || showBack) {
            if (toolbar == null && vsToolbar != null) {
                toolbar = (AppToolbar) vsToolbar.inflate().findViewById(R.id.toolbar);
            }
            if (toolbar != null) {
                toolbar.setTitle("");
                setSupportActionBar(toolbar);
                ActionBar actionBar = getSupportActionBar();
                if (actionBar != null) {
                    if (!isRelativeMode && contentView != null) {
                        RelativeLayout.LayoutParams layoutParams =
                                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                                        RelativeLayout.LayoutParams.MATCH_PARENT);
                        layoutParams.addRule(RelativeLayout.BELOW, R.id.appBarLayout);
                        contentView.setLayoutParams(layoutParams);
                    }
                    actionBar.show();
                    toolbar.setCenterTitle(title);
                    if (resId != 0) {
                        toolbar.setLogo(resId);
                    } else {
//                        actionBar.setDisplayHomeAsUpEnabled(showBack);
                        ImageView ivBack = (ImageView) toolbar.findViewById(R.id.ivBack);
                        ivBack.setVisibility(showBack ? View.VISIBLE : View.GONE);
                        ivBack.setOnClickListener(new MyClickListener() {
                            @Override
                            protected void onMyClick(View v) {
                                onBack();
                            }
                        });
                    }
                }
            }
        } else {
            if (toolbar != null) {
                ActionBar actionBar = getSupportActionBar();
                if (actionBar != null) {
                    actionBar.hide();
                }
            }
        }
    }

    /**
     * 是否是toolbar与contentView是叠加模式
     * 注意：如果为true，请勿重写{@link #setTitle()}方法，
     * 此方法需要在{@link #setTitle(int, boolean)} 或者{@link #setTitle(String, boolean)}之前调用!!!
     *
     * @param relativeMode
     */
    public void setRelativeMode(boolean relativeMode) {
        isRelativeMode = relativeMode;
    }

    /**
     * 设置Title，如果不设置或者返回null将不会显示toolbar
     */
    protected String setTitle() {
        return null;
    }

    /**
     * 设置title
     *
     * @param title    title字符串
     * @param showBack 是否显示返回箭头
     */
    protected void setTitle(String title, boolean showBack) {
        initToolbar(title, showBack, 0);
    }

    protected void setTitle(int resId, boolean showBack) {
        initToolbar(getString(resId), showBack, 0);
    }

    /**
     * 设置一个带logo的title
     *
     * @param title title字符串
     * @param resId logo的资源id
     */
    protected void setTitleWithLogo(String title, int resId) {
        initToolbar(title, false, resId);
    }

    /**
     * toolbar左侧添加布局
     *
     * @param layoutId
     * @param listener
     * @return
     */
    public View setToolbarLeftView(@LayoutRes int layoutId, View.OnClickListener listener) {
        View view = LayoutInflater.from(this).inflate(layoutId, null);
        if (toolbar != null && view != null) {
            return toolbar.addLeftView(view, listener);
        }
        return null;
    }

    /*设置布局*/
    public void setContentView(int layoutResID) {
        if (layoutResID != 0) {
            if (contentView != null) {
                contentView.removeAllViews();
                getLayoutInflater().inflate(layoutResID, contentView);
            } else {
                getDelegate().setContentView(layoutResID);
                toolbar = (AppToolbar) findViewById(R.id.toolbar);
            }
        }
    }

    /**
     * 显示其他非数据页面
     * 若不使用base布局，则需保证自己的布局中有Framelayout,切id是R.id.fl_page_container
     *
     * @param status  0:数据正常,1:正在加载,2:页面为空,3:页面出错
     * @param message
     */
    protected void showStatusPage(int status, String message) {
        if (contentView != null) {
            if (statusView == null) {
                statusView = StatusView.createStatusView(this).setOptionClickListener(this);
                contentView.addView(statusView);
            }
            statusView.showStatusPage(status, message);
            if (status == StatusView.STATUS_NORMAL) {
                contentView.removeView(statusView);
                statusView = null;
            }
        }
    }

    /**
     * 获取根布局
     *
     * @return
     */
    public RelativeLayout getRootView() {
        return rlRootView;
    }

    /**
     * StatusView中的点击事件
     *
     * @param view
     */
    @Override
    public void onOptionClick(View view) {

    }

}
